<?php
namespace app\api\controller;
use app\common\controller\CommonApi;

/**
 * 访客相关
 */
class Visiter extends CommonApi{

    //访客记录
    public function history(){
        $validate = new \think\validate(
            [
                'type' => 'require|in:1,2',
            ],[

                'type.require' => '参数type丢失',
                'type.in' => '类型有误'
            ]
        );

        if($validate->check($this->post) === false){
            $this->apiReturn(0, $validate->getError());
        }

        $lng = $this->user_info['from_lng'];
        $lat = $this->user_info['from_lat'];
   
        $model = db('visiter')->alias('v');
        //谁看过我,被访问者是UID
        if($this->post['type'] == 1){
            $model->join(['bz_user' => 'u'],'u.id = v.visit')->where('user_id',UID);
        }else{ //我看过谁
            $model->join(['bz_user' => 'u'],'u.id = v.user_id')->where('visit',UID);
        }

        $list = $model->limit(($this->p-1)*config('page_size'),config('page_size'))
            ->order('add_time desc')
            ->field("v.id,u.id as user_id,nick_name,sex,photo_path,zhiye,kaopu,sign,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - from_lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(from_lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - from_lng * PI() / 180) / 2),2)))) AS juli,add_time,grade,grade_end_time")
            ->select();

        $data = [];

        foreach($list as $key => $val){
            if($val['grade'] == 1){
                if($val['grade_end_time'] < strtotime(date('Y-m-d'))){
                    $list[$key]['grade'] = 0;
                }
            }
            $val['zhiye'] = $val['zhiye'] == 0 ? "" : db('zhiye')->where('id',$val['zhiye'])->value('name');
            $date = date('Y',$val['add_time']) == date('Y') ? date('n月j日',$val['add_time']) : date('y年n月j日',$val['add_time']);
            
            $dates = array_column($data,'date');
            $keys = array_search($date,$dates);
            if($keys === false){
                $data[] = ['date' => $date,'list' => [$val]];
                continue;
            }

            $data[$keys]['list'][] = $val;

        }
        $this->apiReturn(1,'列表',$data);
    }   

    //删除访问记录
    public function delHistory(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $info = db('visiter')->where('id',intval($this->post['id']))->delete();
        $this->apiReturn(1,'删除成功');
    }

}
